package cn.zswltech.gruul.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2024/3/6 20:58
 */
@Component
public class RedisLuaUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成表主键
     * @param tableName 表名
     * @return
     */
    public Long getTableId(String tableName){
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptText("local id_key = 'id_key_'..KEYS[1];" +
                "local id = redis.call('incr', id_key);"+
                "return tonumber(id);");
        return (Long) redisTemplate.execute(redisScript, Arrays.asList(tableName));
    }

    /**
     * 批量生成id主键
     * @param tableName 表名
     * @param size 大小
     * @return 起始主键id
     */
    public Long getTableId(String tableName,Integer size){
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptText("local id_key = 'ide_key_'..KEYS[1];" +
                "local value = KEYS[2];" +
                "local id = redis.call('incr',id_key);" +
                "redis.call('incrBy',id_key,value-1)" +
                "return tonumber(id);");
        return (Long) redisTemplate.execute(redisScript, Arrays.asList(tableName,size),null);
    }
}
